package db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import model.Dog;

import org.apache.log4j.Logger;

public class DogDAO {
    Logger logger = Logger.getLogger(DogDAO.class);

    public List<Dog> findAll() {
	List<Dog> dogs = new LinkedList<Dog>();
	ResultSet res = DBConnectionHelper
		.executeQuery("SELECT dog_nr, breed, name, age_in_months FROM dog");
	if (res == null) {
	    return null;
	}
	try {
	    while (res.next()) {
		Dog d = new Dog();
		d.setBreed(res.getString("breed"));
		d.setAgeInMonths(res.getInt("age_in_months"));
		d.setDogNr(res.getInt("dog_nr"));
		d.setName(res.getString("name"));
		dogs.add(d);
	    }
	    return dogs;
	} catch (SQLException e) {
	    logger.debug(e.getMessage());
	    return null;
	}
    }

    public Dog findById(int id) {
	ResultSet res = DBConnectionHelper
		.executeQuery("SELECT * FROM dog WHERE dog_nr=" + id);
	if (res == null) {
	    return null;
	}
	try {
	    Dog dog = new Dog();
	    if (res.next()) {
		dog.setBreed(res.getString("breed"));
		dog.setAgeInMonths(res.getInt("age_in_months"));
		dog.setDogNr(res.getInt("dog_nr"));
		dog.setName(res.getString("name"));
		dog.setDescription(res.getString("description"));	
	    }
	    return dog;
	} catch (SQLException e) {
	    logger.debug(e.getMessage());
	    return null;
	}
    }

    public void update(Dog dog) {
	if (dog == null) {
	    return;
	}
	Connection con = DBConnectionHelper.getConnection();
	try {
	    PreparedStatement st = con
		    .prepareStatement("UPDATE dog SET age_in_months= ? , "
			    + "breed= ?, name= ?, description= ? WHERE dog_nr = ?");
	    st.setInt(1, dog.getAgeInMonths());
	    st.setString(2, dog.getBreed());
	    st.setString(3, dog.getName());
	    st.setString(4, dog.getDescription());
	    st.setInt(5, dog.getDogNr());
	    st.execute();
	    st.close();
	    con.close();
	} catch (SQLException e) {
	    logger.error("Error updating dog with id " + dog.getDogNr());
	}

    }

}
